package com.demo.paypalmanagement.common;

import com.alibaba.fastjson2.JSON;
import com.demo.paypalmanagement.model.vo.PaypalVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

@Component
public class PayPalAccessToken {

    @Value("${paypal.client-id}")
    private String clientId;

    @Value("${paypal.client-secret}")
    private String clientSecret;

    @Value("${paypal.token-ip}")
    private String tokenIp;

    public PaypalVO getAccessToken() {
        PaypalVO paypalVO = new PaypalVO();
        try {
            String credentials = clientId + ":" + clientSecret;
            String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());

            URL url = new URL(tokenIp);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);

            String postParameters = "grant_type=client_credentials";
            try (OutputStream os = connection.getOutputStream()) {
                byte[] postParametersBytes = postParameters.getBytes();
                os.write(postParametersBytes);
                os.flush();
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            paypalVO = JSON.parseObject(response.toString(), PaypalVO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paypalVO;
    }
}
